<script setup>
import * as api from "@/api/v-sys-service/exam/template";
import { page } from "@/api/v-sys-service/exam/question"
import Constants from "@/const/index.js";

const emits = defineEmits([
  'query',
  'update:modelValue'
])

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => {}
  }
})


/**
 * 分页参数
 */
const pageQuery = reactive({
  page: 1,
  limit: 100,
  total: 0,
  url: '/cloud-sys-service/exam-question/page',
  orders: [
    {column: "createTime", asc: false}
  ],
  filters: [],
  condition: {
    key: "",
    groupId: props.rowData.groupId
  },
})

const formData = ref({
  id: '',//
  examName: '',//考试名称
  groupId: '',// 题库
  fullScore: '',//满分
  passScore: 0,//及格分
  questionTotal: '',//题目数量
  carefulNotice: '',//注意事项
  examQuestions: [], //试题列表
})

const saveBtnLoading = ref(false)
const formRef = ref()

const questionGroupOptions = ref([])
const checkData = (rule, value, callback) => {
  if (value) {
    if (/[\u4E00-\u9FA5]/g.test(value)) {
      callback(new Error('编码不能输入汉字!'));
    } else {
      callback();
    }
  }
  callback();
}

const validPassScore = (rule, value, callback) => {
  if (value <= 0) {
    callback(new Error('及格分必须大于0!'));
  }
  callback();
}

const rules = ref({
  accessKey: [
    { validator: checkData, trigger: 'change' },
    { required: true, message: "请输入AccessKey ID", trigger: "blur" }
  ],
  examName: [
    { required: true, message: "请输入试卷名称", trigger: "change" },
  ],
  passScore: [
    { validator: validPassScore, trigger: 'change' },
    { required: true, message: "请输入及格分", trigger: "blur" },
  ],
  channelNameCode: [{ required: true, message: "渠道名称不能为空", trigger: "blur" }],
})

const loading = ref(false)

const tableData = ref([])

const optionTags = ref([
  'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'
])

const visible = computed(
    {
      get(){
        return props.modelValue
      },
      set(val){
        emits('update:modelValue',val)
      }
    }
)

const title = computed(
    () => {
      return props.rowData && props.rowData.id ? '编辑' : '新增'
    }
)

const fullScore = computed(
    () => {
      let sum = 0
      tableData.value.forEach(ele => sum += ele.questionScore)
      return sum
    }
)
watch(
    props.rowData,
    (val) =>{
      if (val && val.id) Object.assign(formData.value,val)
      if (val.groupId) formData.value.groupId = val.groupId
    },
    {
      immediate: true,
    }
)
onMounted(()=>{
  init()
})
const init = () => {
  init_Data()
  init_Cache()
}

/**
 * 初始化数据
 */
const init_Data = () => {
  formData.value.id ? init_Info() : init_Question()
}

/**
 * 数据回显
 */
const init_Info = async () => {
  const { code, data } = await api.infoExam(formData.value.id)
  if (code === 200) {
    Object.assign(formData.value,data)
    tableData.value = formData.value.examQuestions
  }
}

/**
 * 分页查询试题
 */
const init_Question = async () => {
  loading.value = true
  const { code, data } = await page(pageQuery)
  if (code === 200) {
    loading.value = false
    tableData.value = data.records
    pageQuery.total = data.total
    refresh()
  }
}

const init_Cache = () => {

}
const sure = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      saveBtnLoading.value = true
      const { code } = await api.createExam(formData.value)
      saveBtnLoading.value = false
      if (code === 200){
        visible.value = false
        ElMessage({message: '成功生成试卷模板', type: 'success',})
        emits('query')
      }
    }
  })
}

/**
 * 删除题目
 */
const removeQue = (index) => {
  tableData.value.splice(index, 1)
  refresh()
}

/**
 * 刷新总分、题目数量
 */
const refresh = () => {
  formData.value.fullScore = fullScore.value
  formData.value.questionTotal = tableData.value.length
  formData.value.examQuestions = tableData.value
}

</script>

<template>
  <v-dialog v-model="visible" width="60%" :loading="saveBtnLoading" :title="title" @sure="sure">
    <div class="form">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="考试名称：" prop="examName">
              <el-input v-model="formData.examName"></el-input>
            </el-form-item>
          </el-col>
<!--          <el-col :span="12">
            <el-form-item label="题库：" prop="groupId">
              <el-select disabled v-model="formData.groupId" filterable clearable>
                <el-option
                    v-for="item in questionGroupOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>-->
          <el-col :span="8">
            <el-form-item label="题目数量：">
              <el-input v-model="formData.questionTotal" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="满分：">
              <el-input v-model="formData.fullScore" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="及格分：" prop="passScore">
              <el-input-number
                  v-model="formData.passScore" controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="注意事项：" prop="carefulNotice">
              <el-input v-model="formData.carefulNotice" type="textarea" show-word-limit
                        :autosize="{ minRows: 2, maxRows: 5}" maxlength="300"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="elDividerBox">
          <span class="line"></span>
          <span class="text">试题列表</span>
          <span class="line"></span>
        </div>
        <vxe-table border :data="tableData" height="400px">
          <vxe-column
              title="题目类型"
              align="center"
              field="questionType"
              width="80px"
          >
            <template #default="{row}">
              <el-tag v-if="row.questionType === Constants.RADIO" type="warning">单选题</el-tag>
              <el-tag v-if="row.questionType === Constants.CHECK" type="success">多选题</el-tag>
              <el-tag v-if="row.questionType === Constants.TRUE_FALSE" type="primary">判断题</el-tag>
            </template>
          </vxe-column>
          <vxe-column
              title="题目分值"
              align="center"
              field="questionScore"
              width="80px"
          >
          </vxe-column>
          <vxe-column
              title="题目内容"
              align="center"
              field="questionContent"
              min-width="350px"
          >
          </vxe-column>
          <vxe-column
              title="操作"
              align="center"
              width="80px"
              fixed="left"
          >
            <template #default="{rowIndex}">
<!--              {{rowIndex}}-->
              <el-button type="primary" :text="true" size="small" @click="removeQue(rowIndex)">
                <template #icon><i-ep-delete /></template>删除
              </el-button>
            </template>
          </vxe-column>
          <vxe-column
              align="center"
              width="100"
              type="expand"
              title="题目选项"
              fixed="left"
          >
            <template #content="{ row }">
              <vxe-table class="expand-wrapper" border :data="row.answerOptions">
                <vxe-column
                    field="optionTag"
                    min-width="60"
                    title="选项"
                >
                  <template #default="{rowIndex}">{{row.optionTag ? row.optionTag : optionTags[rowIndex]}}</template>
                </vxe-column>
                <vxe-column
                    field="answer"
                    min-width="400"
                    title="选项内容"
                ></vxe-column>
                <vxe-column
                    field="isRightAnswer"
                    min-width="60"
                    title="是否正确答案"
                >
                  <template #default="{row}">{{row.isRightAnswer ? '是': '否'}}</template>
                </vxe-column>
              </vxe-table>
            </template>
          </vxe-column>
        </vxe-table>
      </el-form>
    </div>
  </v-dialog>
</template>

<style scoped lang="scss">
.form {
  .el-form-item {
    :deep(.el-form-item__content) {
      .el-input-number {
        width: 100%;
        .el-input {
          width: 100%;
        }
      }
    }
  }
}
.elDividerBox {
  .line {
    width: calc(50% - 55px);
  }

  .text {
    width: 100px;
    text-align: center;
  }
}
.expand-wrapper {
  padding: 20px 40px;
}
</style>
